/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package me.weyye.hipermission;

import ohos.agp.colors.RgbColor;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.render.BlendMode;
import ohos.agp.render.ColorMatrix;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 列表适配器
 *
 * @since 2021-04-12
 */
public class PermissionItemProvider extends BaseItemProvider {
    private List<PermissionItem> mData;
    private int mTextColor;
    private int mFilterColor;

    private int column;

    /**
     * PermissionItemProvider
     *
     * @param data 列表数据
     */
    public PermissionItemProvider(List<PermissionItem> data) {
        mData = data;
        if (mData.size() >= 3) {
            column = 3;
        } else {
            column = mData.size();
        }
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int i) {
        return mData.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
        Context context = componentContainer.getContext();
        PermissionItem item = mData.get(position);
        Component component = LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_permission_info_item, null, false);
        int width = componentContainer.getEstimatedWidth();
        if (width > 0) {
            component.setLayoutConfig(
                    new ComponentContainer.LayoutConfig(componentContainer.getEstimatedWidth() / column,
                            ComponentContainer.LayoutConfig.MATCH_CONTENT));
        } else {
            component.setMarginsLeftAndRight(AttrHelper.vp2px(15, context),
                    AttrHelper.vp2px(15, context));
        }
        Image icon = (Image) component.findComponentById(ResourceTable.Id_icon);
        Text name = (Text) component.findComponentById(ResourceTable.Id_name);

        if (mTextColor != 0) {
            name.setTextColor(new Color(mTextColor));
        }
        int color = context.getColor(mFilterColor);
        PixelMap pixelMap = getPixelMap(context, item.PermissionIconRes);
        if (pixelMap != null) {
            PixelMapElement element = new PixelMapElement(pixelMap);
            element.setColorMatrix(new ColorMatrix(new float[]{
                1, 0, 0, 0, RgbColor.fromArgbInt(color).getRed(),// 红色值
                0, 1, 0, 0, RgbColor.fromArgbInt(color).getGreen(),// 绿色值
                0, 0, 1, 0, RgbColor.fromArgbInt(color).getBlue(),// 蓝色值
                0, 0, 0, 1, 1 // 透明度
            }));
            element.setStateColorMode(BlendMode.SRC_ATOP);
            icon.setImageElement(element);
        }
        name.setText(item.PermissionName);
        return component;
    }

    /**
     * 通过图片ID返回PixelMap
     *
     * @param context 上下文
     * @param resourceId 图片的资源ID
     * @return PixelMap
     */
    public static PixelMap getPixelMap(Context context, int resourceId) {
        HiLogLabel label = new HiLogLabel(0, 0x000001, "getPixelMap");
        InputStream inputStream = null;
        ImageSource imageSource = null;
        ImageSource.DecodingOptions decodingOptions = null;
        try {
            // 创建图像数据源ImageSource对象
            inputStream = context.getResourceManager().getResource(resourceId);
            ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
            srcOpts.formatHint = "image/png";
            imageSource = ImageSource.create(inputStream, srcOpts);

            // 设置图片参数
            decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.desiredSize = new Size(AttrHelper.vp2px(54, context),
                    AttrHelper.vp2px(54, context));
        } catch (IOException e) {
            HiLog.error(label, "IOException: " + e.getMessage());
        } catch (NotExistException e) {
            HiLog.error(label, "NotExistException: " + e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    HiLog.error(label, "IOException: " + e.getMessage());
                }
            }
        }
        if (imageSource == null) {
            return null;
        } else {
            return imageSource.createPixelmap(decodingOptions);
        }
    }

    /**
     * 设置文字颜色
     *
     * @param itemTextColor 颜色值
     */
    public void setTextColor(int itemTextColor) {
        mTextColor = itemTextColor;
        notifyDataChanged();
    }

    /**
     * 设置图标颜色
     *
     * @param filterColor 颜色值
     */
    public void setFilterColor(int filterColor) {
        mFilterColor = filterColor;
        notifyDataChanged();
    }
}
